package cn.qpyl.longpoll.netty;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
public class Main {
    public static void main(String[] args) {

        int port = 8000;
        String pStr =System.getProperty("port");
        if (null != pStr){
            port = Integer.parseInt(pStr);
        }
        System.out.println("Netty Main");

        EventLoop el = new EventLoop("main");

        App app = App.Default();

        app.Get("/hello", (req) -> {
            return req.response();
        });

        app.Post("/hello", (req) -> {
            return req.response();
        });

        App v1 = app.Group("/longpolling");
        {
            v1.Get("/hello", (req) -> {
                log.info("On long poll hello ..................");
                Function<Object, Boolean> func = data -> {
                    if (null == data) {
                        int i = new Random().nextInt();
                        log.info("rd value =============== {}", i);
                        if (i % 5 == 0) {
                            req.response("SUCCESS");
                            return true;
                        }
                        return false;
                    } else {
                        req.response(data);
                        return true;
                    }
                };
                Consumer<Object> c = el.createRepeatTask(func, 1 * 1000L, 20 * 1000L);
                // c.accept(null);

                return true;
            });
        }

        app.Run(port);
    }
}